import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

import '../model/health_record.dart';
import '../service/database_service.dart';

class AddMilestoneRecordDialog extends StatefulWidget {
  final String babyId;
  const AddMilestoneRecordDialog({Key? key, required this.babyId})
    : super(key: key);

  @override
  State<AddMilestoneRecordDialog> createState() =>
      _AddMilestoneRecordDialogState();
}

class _AddMilestoneRecordDialogState extends State<AddMilestoneRecordDialog> {
  final _formKey = GlobalKey<FormState>();
  DateTime _date = DateTime.now();
  final _titleController = TextEditingController();
  final _descriptionController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('添加里程碑'),
      content: Form(
        key: _formKey,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _buildDatePicker(),
            TextFormField(
              controller: _titleController,
              decoration: const InputDecoration(labelText: '里程碑名称'),
              validator: (value) => value?.isEmpty ?? true ? '请输入里程碑名称' : null,
            ),
            TextFormField(
              controller: _descriptionController,
              decoration: const InputDecoration(labelText: '描述'),
              maxLines: 3,
            ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('取消'),
        ),
        TextButton(onPressed: _submit, child: const Text('保存')),
      ],
    );
  }

  Widget _buildDatePicker() {
    return InkWell(
      onTap: () async {
        final picked = await showDatePicker(
          context: context,
          initialDate: _date,
          firstDate: DateTime(2020),
          lastDate: DateTime.now(),
        );
        if (picked != null) {
          setState(() => _date = picked);
        }
      },
      child: InputDecorator(
        decoration: const InputDecoration(labelText: '日期'),
        child: Text(DateFormat('yyyy-MM-dd').format(_date)),
      ),
    );
  }

  void _submit() async {
    if (!_formKey.currentState!.validate()) return;

    try {
      await DatabaseService().addHealthRecord(
        HealthRecord(
          babyId: widget.babyId,
          type: RecordType.milestone,
          timestamp: _date,
          data: {
            'title': _titleController.text,
            'description': _descriptionController.text,
          },
        ),
      );
      if (mounted) Navigator.pop(context);
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('保存失败: $e')));
      }
    }
  }

  @override
  void dispose() {
    _titleController.dispose();
    _descriptionController.dispose();
    super.dispose();
  }
}
